<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>server配置</title>
    <link rel="stylesheet" href="/component/pear/css/pear.css">
</head>
<body style="padding: 15px;">
<div style="display: flex;">
    <button type="button" class="layui-btn layui-btn-normal" id="addConf">添加配置</button>

    <div class="layui-form">
        <div class="layui-inline">
            <label class="layui-form-label">选择添加</label>
            <div class="layui-input-block">
                <select name="type" lay-verify="required">
                    <option value="proxy">反向代理</option>
                    <option value="static">部署静态资源</option>
                    <option value="ssl">配置SSL</option>
                    <option value="hn">忽略域名或主机ip</option>
                    <option value="3">深圳</option>
                    <option value="4">杭州</option>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <button type="button" lay-submit lay-filter="formDemo" class="layui-btn layui-btn-normal">快速添加</button>
        </div>
    </div>
    <button type="button" class="layui-btn layui-btn-normal" id="see">查看server配置</button>
</div>
<div style="padding: 16px;">
    <table class="layui-hide" id="table" lay-filter="test"></table>
</div>
<script type="text/html" id="barDemo">
    <div class="layui-clear-space">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
    </div>
</script>
<script type="text/html" id="ID-table-demo-templet-switch">
    <!-- 这里的 checked 的状态值判断仅作为演示 -->
    <input type="checkbox" name="{{= d.name }}" value="{{= d.id }}" title="启用|" lay-skin="switch"
           lay-filter="demo-templet-status" {{=d.status==='1'?"checked":""}}>
</script>
</body>
<script type="text/javascript" src="/component/layui/layui.js"></script>
<script type="text/javascript" src="/component/pear/pear.js"></script>
<script>
    layui.use(['table', 'dropdown', 'form', 'jquery']);
    var table = layui.table;
    var dropdown = layui.dropdown;
    var form = layui.form;
    var $ = layui.jquery

    function GetQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
        var context = "";
        if (r != null)
            context = decodeURIComponent(r[2]);
        reg = null;
        r = null;
        return context === null || context === "" || context === "undefined" ? "" : context;
    }

    var serverId = GetQueryString('id');
    // 创建渲染实例
    table.render({
        elem: '#table',
        url: '/nginx/server/item?id=' + serverId, // 此处为静态模拟数据，实际使用时需换成真实接口
        height: 'full-35', // 最大高度减去其他容器已占有的高度差
        cellMinWidth: 80,
        totalRow: true, // 开启合计行
        page: false,
        cols: [[
            {field: 'id', width: 10, title: 'id', hide: true},
            {field: 'name', width: 150, title: '名称'},
            {field: 'value', width: 300, title: '值'},
            {field: 'description', width: 250, title: '描述'},
            {field: 'status', width: 100, title: '是否启用', templet: '#ID-table-demo-templet-switch'},
            {fixed: 'right', title: '操作', width: 160, minWidth: 150, toolbar: '#barDemo'}
        ]],
        done: function () {
        },
        error: function (res, msg) {
            console.log(res, msg)
        }
    });

    // 触发单元格工具事件
    table.on('tool(test)', function (obj) { // 双击 toolDouble
        var data = obj.data; // 获得当前行数据
        if (obj.event === 'edit') {
            layer.prompt(
                {
                    title: '编辑配置',
                    formType: 2,
                    value: data.name,
                    offset: 't',
                    area: ['700px', '400px'],
                    placeholder: '名称，例如：listen',
                    success: function (layero, index, that) {
                        $('.layui-layer-content .layui-layer-input').css('height', '50px')
                        $(".layui-layer-content").append('<br/><textarea spellcheck="true" style="height: 200px" id="value1" placeholder="值，例如：listen" class="layui-textarea"></textarea>')
                        $(".layui-layer-content").append('<br/><textarea spellcheck="true" style="height: 100px" id="description1" placeholder="描述，例如：server监听端口" class="layui-textarea"></textarea><br/>')
                        $('#value1').val(data.value)
                        $('#description1').val(data.description)
                    }
                },
                function (value, index, elem) {
                    $.ajax({
                        data: {
                            id: data.id,
                            name: value,
                            value: $('#value1').val(),
                            description: $('#description1').val()
                        },
                        url: '/nginx/server/item',
                        type: 'put',
                        success(res) {
                            layer.msg(res.msg)
                            if (res.code === 0) {
                                setTimeout(() => {
                                    window.location.reload()
                                }, 800)
                            }
                        }
                    })
                });
        } else if (obj.event === 'delete') {
            if (data.name === 'listen') {
                layer.msg('端口配置不可删除！')
                return
            }
            layer.confirm(`确认删除<b style="color: red"> ${data.name} </b> 吗？`,
                {title: '提示'},
                function (i, y) {
                    $.ajax({
                        data: {id: data.id},
                        url: '/nginx/server/item',
                        type: 'delete',
                        success(res) {
                            layer.msg(res.msg)
                            if (res.code === 0)
                                setTimeout(() => {
                                    window.location.reload()
                                }, 800)
                        }
                    })
                });
        }
    });

    // 状态 - 开关操作
    form.on('switch(demo-templet-status)', function (obj) {
        if (this.name === 'listen') {
            layer.msg('端口配置不可关闭！')
            setTimeout(function () {
                window.location.reload()
            }, 800)
            return
        } else {
            $.ajax({
                url: '/nginx/server/itemStatus',
                data: {id: this.value},
                type: 'put',
                success(data) {
                    layer.msg(data.msg)
                }
            })
        }

    });

    function addConf(val) {
        if (!val.name)
            val = {name: '', value: '', description: ''}
        layer.prompt(
            {
                title: '添加配置',
                formType: 2,
                value: val.name,
                offset: 't',
                area: ['700px', '400px'],
                placeholder: '名称，例如：listen',
                success: function (layero, index, that) {
                    $('.layui-layer-content .layui-layer-input').css('height', '50px')
                    $(".layui-layer-content").append('<br/><textarea spellcheck="true" style="height: 200px" id="value2" placeholder="值，例如：listen" class="layui-textarea">' + val.value + '</textarea>')
                    $(".layui-layer-content").append('<br/><textarea style="height: 100px" id="description2" placeholder="描述，例如：server监听端口" class="layui-textarea">' + val.description + '</textarea><br/>')
                }
            },
            function (value, index, elem) {
                $.ajax({
                    data: {
                        description: $('#description2').val(),
                        value: $('#value2').val(),
                        name: value,
                        serverId: serverId
                    },
                    url: '/nginx/server/item',
                    type: 'post',
                    success(res) {
                        layer.msg(res.msg)
                        if (res.code === 0) {
                            setTimeout(() => {
                                window.location.reload()
                            }, 800)
                        }
                    }
                })
            });
    }

    $('#addConf').on('click', function () {
        addConf({})
    })


    var index = 0;
    //监听提交
    form.on('submit(formDemo)', function (data) {
        // layer.msg(JSON.stringify(data.field));
        var type = data.field.type
        if (type === 'proxy') {
            addConf({
                name: 'location',
                value: `/${index++} {
                add_header Access-Control-Allow-Origin *;
                add_header Access-Control-Allow-Headers X-Requested-With;
                add_header Access-Control-Allow-Methods GET,POST,DELETE,PUT,OPTIONS;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Real-Port $remote_port;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_pass http://127.0.0.1:8080;
                }`,
                description: '反向代理' + index
            })
        } else if (type === 'static') {
            addConf({
                name: 'location',
                value: `/${index++} {
                root   /home/app/dist/;
                index  index.html;
                }`,
                description: '静态资源' + index
            })
        } else if (type === 'hn') {
            addConf({
                name: 'server_name',
                value: '_',
                description: '忽略域名或主机ip'
            })
        } else if (type === 'ssl') {
            addConf({
                name: 'server_name',
                value: ``,
                description: '忽略域名或主机ip'
            })
        }
        return false;
    });


    function addConf2(val) {
        if (!val.name)
            val = {name: '', value: '', description: ''}
        layer.prompt(
            {
                title: '添加配置',
                formType: 2,
                value: val.name,
                offset: 't',
                area: ['700px', '400px'],
                placeholder: '名称，例如：listen',
                success: function (layero, index, that) {
                    $('.layui-layer-content .layui-layer-input').css('height', '50px')
                    $(".layui-layer-content").append('<br/><textarea spellcheck="true" style="height: 200px" id="value2" placeholder="值，例如：listen" class="layui-textarea">' + val.value + '</textarea>')
                    $(".layui-layer-content").append('<br/><textarea style="height: 100px" id="description2" placeholder="描述，例如：server监听端口" class="layui-textarea">' + val.description + '</textarea><br/>')
                }
            },
            function (value, index, elem) {
                $.ajax({
                    data: {
                        description: $('#description2').val(),
                        value: $('#value2').val(),
                        name: value,
                        serverId: serverId
                    },
                    url: '/nginx/server/item',
                    type: 'post',
                    success(res) {
                        layer.msg(res.msg)
                        if (res.code === 0) {
                            setTimeout(() => {
                                window.location.reload()
                            }, 800)
                        }
                    }
                })
            });
    }

</script>
</html>
